package com.itany.ums.servlet;

import com.itany.ums.entity.User;
import com.itany.ums.service.UserService;
import com.itany.ums.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2022-11-21 16:45
 * Description：<描述>
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if("/showRegister.user".equals(path)){
            showRegister(req,resp);
        }else if("/register.user".equals(path)){
            register(req,resp);
        }

    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User u = new User();
        u.setUsername(req.getParameter("username"));
        u.setPassword(req.getParameter("password"));
        u.setAge(Integer.parseInt(req.getParameter("age")));

        try {
            userService.register(u);
            req.getRequestDispatcher("/WEB-INF/views/success.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("errorMsg","注册失败！");
            req.getRequestDispatcher("/WEB-INF/views/register.jsp").forward(req,resp);
        }
    }

    private void showRegister(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/views/register.jsp").forward(req,resp);
    }
}
